package com.powerunion.datacollection.dao;

import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.config.ConfigUtil;
import com.powerunion.util.log.LogHelper;


/**
 * @author Alex Zeng
 *
 */
public class DaoFactory {
    private Properties classMap = null;
    private static Logger logger = LogHelper.getInstance().getLogger(DaoFactory.class);
    private static DaoFactory instance = null;

    private DaoFactory() {
        this.classMap = new Properties();
        try {
            String path = ConfigUtil.getInstance().getParameter("dao.mapping.properties");
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
            this.classMap.load(in);
            in.close();
        } catch (IOException e) {
            logger.error("", e);
            throw new SystemException(e.getMessage());
        }
    }

    public static DaoFactory getInstance() {
        if(instance == null)
            instance = new DaoFactory();
        return instance;
    }

    public Object getDao(String dao) {
        String className = null;
        className = this.classMap.getProperty(dao);
        if (className == null || className.trim().equals("")) {
            throw new SystemException("not find dao(" + dao +
                                   ") mapping define!");
        }
        try {
            return Class.forName(className).newInstance();
        } catch (Exception e) {
            logger.error("", e);
            throw new SystemException("get dao error: " + className);
        }
    }

    public Object getDao(Class daoClass){
        return this.getDao(daoClass.getName());
    }

}
